package com.kiss.fw.command;

import org.apache.log4j.Logger;

import com.kiss.fw.dto.AbstractDTO;
import com.kiss.fw.exceptions.CommandException;
import com.kiss.fw.exceptions.CommandInitializeException;
import com.kiss.fw.utils.Constants;
import com.kiss.fw.utils.Util;

public abstract class AbstractCommand {
	private static final Logger logger = Logger.getLogger(AbstractCommand.class);
	private boolean processCommand = true;
	
	protected abstract void initialize() throws CommandInitializeException;
	protected abstract void authorize(AbstractDTO _dto) throws SecurityException;
	protected abstract void preProcess(AbstractDTO _dto) throws CommandException;
	protected abstract void process(AbstractDTO _dto) throws CommandException;
	protected abstract void postProcess(AbstractDTO _dto) throws CommandException;
	
	protected AbstractCommand() {
		initialize();
	}
	
	public boolean isAuthorized() {
		return true;
	}
	
	public void execute(AbstractDTO _dto) throws CommandException {
		try {
			authorize(_dto);
			preProcess(_dto);
			
			if(processCommand) {
				process(_dto);
			}
			
			postProcess(_dto);
		}
		catch(Exception _exception) {
			handleException(logger, "Error executing command", _exception);
		}
	}
	
	public boolean isProcessCommand() {
		return processCommand;
	}
	
	public void setProcessCommand(final boolean _processCommand) {
		processCommand = _processCommand;
	}
	
	protected static void handleException(final Logger _logger, final String _message, Exception _exception) throws CommandException {
		Util.handleException(_logger, _message, _exception);
		
		// throw singleton command exception
		throw Constants.Exceptions.COMMAND_EXCEPTION;
	}
}